package app.fitness.fragment;

import singleton.SingleTon;
import utils.Utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Space;

import com.razerzone.android.fitness.ActivityFitness;
import com.razerzone.android.fitness.R;

import define.Constants;
import define.Key;
import define.Language;

public class GoalSettingsFragment extends Fragment implements OnClickListener,
		OnFocusChangeListener, OnSeekBarChangeListener, OnKeyListener {

	/**
	 * Fragment
	 */
	private Fragment mFm = null;

	/**
	 * Listener
	 */
	// private OnClickListener mListernerBack = new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// Fragment mFm = new DashBoardFragment();
	// getFragmentManager().beginTransaction()
	// .replace(R.id.fr_content_activity_fitness, mFm)
	// .commitAllowingStateLoss();
	// getActivity().runOnUiThread(new Runnable() {
	//
	// @Override
	// public void run() {
	// getActivity().getSupportFragmentManager()
	// .executePendingTransactions();
	// }
	// });
	// }
	// };

	/**
	 * Shared Preference
	 */
	private static SharedPreferences mSp;
	public static SharedPreferences.Editor mSpEditor;

	/**
	 * String section
	 */
	public static boolean IS_GO_TO_DASHBOARD_PAGE_FROM_GOAL_PAGE = false;
	public static boolean IS_IN_GOAL_PAGE = false;

	public static final String TAG = GoalSettingsFragment.class.getSimpleName();

	/**
	 * View section
	 */
	private Button mBtnBack;
	private Button mBtnNext;
	private static EditText mEtCalories;
	private static EditText mEtDistance;
	// private EditText mTvFloors;
	private static EditText mEtSleep;
	private static EditText mEtSteps;
	private LinearLayout mLlGoalSettings;
	private LinearLayout mLlIncludedButton;
	private SeekBar mSbActiveMins;
	private SeekBar mSbCalories;
	private SeekBar mSbDistance;
	// private SeekBar mSbFloors;
	private SeekBar mSbSleep;
	private SeekBar mSbSteps;
	private Space mSpace;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back_in_goal:
			// From here, check fragment class name
			// to decide when we clicked BACK button in Goal fragment
			// Where it go
			if (DashBoardFragment.IS_GO_FROM_DASHBOARD_TO_GOAL_PAGE) {
				mFm = new SettingsFragment();
				// Transfer to Personal Data fragment
				getFragmentManager().beginTransaction()
						.replace(R.id.fr_content_activity_fitness, mFm)
						// .addToBackStack(null)
						.commitAllowingStateLoss();
			} else {
				mFm = new PersonalDataFragment();
				// Transfer to Personal Data fragment
				getFragmentManager().beginTransaction()
						.replace(R.id.fr_content_activity_fitness, mFm)
						// .addToBackStack(null)
						.commitAllowingStateLoss();
			}
			break;
		case R.id.btn_next_in_goal:
			mFm = new DashBoardFragment();
			// Transfer to Dash board fragment
			getFragmentManager().beginTransaction()
					.replace(R.id.fr_content_activity_fitness, mFm)
					// .addToBackStack(null)
					.commitAllowingStateLoss();
			break;
		case R.id.et_calories_in_goal:
			setCursorAtFirstIndex();
			setDefaultState();

			mEtCalories.setBackgroundResource(R.drawable.bg_goal_focus);
			mEtCalories.setCursorVisible(true);
			mEtCalories.setTextColor(Color.WHITE);
			mSbCalories.setProgress(Integer.valueOf(mEtCalories.getText()
					.toString()));
			break;
		case R.id.et_distance_in_goal:
			setCursorAtFirstIndex();
			setDefaultState();

			mEtDistance.setBackgroundResource(R.drawable.bg_goal_focus);
			mEtDistance.setCursorVisible(true);
			mEtDistance.setTextColor(Color.WHITE);
			mSbDistance.setProgress(Integer.valueOf(mEtDistance.getText()
					.toString()));
			break;
		case R.id.et_sleep_in_goal:
			setCursorAtFirstIndex();
			setDefaultState();

			mEtSleep.setBackgroundResource(R.drawable.bg_goal_focus);
			mEtSleep.setCursorVisible(true);
			mEtSleep.setTextColor(Color.WHITE);
			mSbSleep.setProgress(Integer.valueOf(mEtSleep.getText().toString()));

			break;
		case R.id.et_steps_in_goal:
			setCursorAtFirstIndex();
			setDefaultState();

			mEtSteps.setBackgroundResource(R.drawable.bg_goal_focus);
			mEtSteps.setCursorVisible(true);
			mEtSteps.setTextColor(Color.WHITE);
			mSbSteps.setProgress(Integer.valueOf(mEtSteps.getText().toString()));
			break;
		case R.id.ll_goal_settings:
			mEtCalories.clearFocus();
			mEtDistance.clearFocus();
			mEtSleep.clearFocus();
			mEtSteps.clearFocus();

			setDefaultState();

			mSbCalories.setProgress(Integer.valueOf(mEtCalories.getText()
					.toString()));
			mSbDistance.setProgress(Integer.valueOf(mEtDistance.getText()
					.toString()));
			mSbSleep.setProgress(Integer.valueOf(mEtSleep.getText().toString()));
			mSbSteps.setProgress(Integer.valueOf(mEtSteps.getText().toString()));

			Constants.utils.hideSoftKeyboard(mEtCalories);
			Constants.utils.hideSoftKeyboard(mEtDistance);
			Constants.utils.hideSoftKeyboard(mEtSleep);
			Constants.utils.hideSoftKeyboard(mEtSteps);
			break;
		default:
			break;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		IS_IN_GOAL_PAGE = true;

		mSp = getActivity()
				.getSharedPreferences(Constants.PREFERENCES_GOALS, 0);
		mSpEditor = mSp.edit();

		/**
		 * Check Action Bar is shown or not, if shown, need adjust title page is
		 * center, and hide Next button
		 */
		if (getActivity().getActionBar().isShowing()) {
			// Set title
			ActivityFitness.mTvTitle.setText(R.string.goal_settings_);

			// Show title
			ActivityFitness.mTvTitle.setVisibility(View.VISIBLE);

			/**
			 * Set Title Page is center
			 */
			switch (Utils.checkLanguageInSettings()) {
			case Language.CHINESE:
				ActivityFitness.mIvActionBar.setLayoutParams(new LayoutParams(
						Utils.getWidth(getActivity()) / 4,
						android.view.ViewGroup.LayoutParams.MATCH_PARENT));
				break;
			case Language.ENGLISH:
				ActivityFitness.mIvActionBar.setLayoutParams(new LayoutParams(
						Utils.getWidth(getActivity()) / 4 - 100,
						android.view.ViewGroup.LayoutParams.MATCH_PARENT));
				break;
			}
		}

		// Set background color for drawer item when was chose
		ActivityFitness.mLLAbout.setBackgroundColor(Color.TRANSPARENT);
		ActivityFitness.mLLDashBoard.setBackgroundColor(Color.TRANSPARENT);
		ActivityFitness.mLLGoalSettings.setBackgroundColor(getResources()
				.getColor(R.color.green));

		/**
		 * Set Orientation for page
		 */
		getActivity().setRequestedOrientation(
				ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		View v = inflater.inflate(R.layout.fragment_goal_settings, container,
				false);

		initialVariables(v);
		initialData();

		/**
		 * Check Action Bar is shown or not, if shown, need adjust title page is
		 * center, and hide Next button
		 */
		if (getActivity().getActionBar().isShowing()) {
			/**
			 * Hide Next button
			 */
			mLlIncludedButton.setVisibility(View.GONE);
			mSpace.setVisibility(View.GONE);
		}

		return v;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();

		if (Constants.utils != null) {
			// Hide soft key board
			Constants.utils.hideSoftKeyboard(mEtCalories);
			Constants.utils.hideSoftKeyboard(mEtDistance);
			Constants.utils.hideSoftKeyboard(mEtSleep);
			Constants.utils.hideSoftKeyboard(mEtSteps);
		}

		saveGoalValueIntoSingleTon();
		saveGoalValueIntoSharedPreferences(getActivity());

		IS_GO_TO_DASHBOARD_PAGE_FROM_GOAL_PAGE = true;
		IS_IN_GOAL_PAGE = false;
	}

	@Override
	public void onFocusChange(View v, boolean check) {
		setCursorAtFirstIndex();
		setDefaultState();

		int resid = R.drawable.bg_goal_focus;
		switch (v.getId()) {
		case R.id.et_calories_in_goal:
			mEtCalories.setBackgroundResource(resid);
			mEtCalories.setCursorVisible(true);
			mEtCalories.setTextColor(Color.WHITE);
			mSbCalories.setProgress(Integer.valueOf(mEtCalories.getText()
					.toString()));
			break;
		case R.id.et_distance_in_goal:
			mEtDistance.setBackgroundResource(resid);
			mEtDistance.setCursorVisible(true);
			mEtDistance.setTextColor(Color.WHITE);
			mSbDistance.setProgress(Integer.valueOf(mEtDistance.getText()
					.toString()));
			break;
		case R.id.et_sleep_in_goal:
			mEtSleep.setBackgroundResource(resid);
			mEtSleep.setCursorVisible(true);
			mEtSleep.setTextColor(Color.WHITE);
			mSbSleep.setProgress(Integer.valueOf(mEtSleep.getText().toString()));

			break;
		case R.id.et_steps_in_goal:
			mEtSteps.setBackgroundResource(resid);
			mEtSteps.setCursorVisible(true);
			mEtSteps.setTextColor(Color.WHITE);
			mSbSteps.setProgress(Integer.valueOf(mEtSteps.getText().toString()));
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_ENTER) {
			setCursorAtFirstIndex();
			setDefaultState();

			mSbCalories.setProgress(Integer.valueOf(mEtCalories.getText()
					.toString()));
			mSbDistance.setProgress(Integer.valueOf(mEtDistance.getText()
					.toString()));
			mSbSleep.setProgress(Integer.valueOf(mEtSleep.getText().toString()));
			mSbSteps.setProgress(Integer.valueOf(mEtSteps.getText().toString()));
		}
		return false;
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		/**
		 * Create Goal object to store data value
		 */
		// Set data value of seek bar
		switch (seekBar.getId()) {
		case R.id.sb_active_mins_in_goal:
			break;
		case R.id.sb_calories_in_goal:
			mEtCalories.setText(progress + "");
			break;
		case R.id.sb_distance_in_goal:
			mEtDistance.setText(progress + "");
			break;
		case R.id.sb_sleep_in_goal:
			mEtSleep.setText(progress + "");
			break;
		case R.id.sb_steps_in_goal:
			mEtSteps.setText(progress + "");
			break;
		default:
			break;
		}
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
	}

	/**
	 * Initialize methods
	 */

	private void initialData() {
		setCursorAtFirstIndex();
		setDefaultState();

		// Set listener
		mBtnBack.setOnClickListener(this);
		mBtnNext.setOnClickListener(this);

		mLlGoalSettings.setOnClickListener(this);
		// mLlGoalSettings.setOnTouchListener(this);

		mSbActiveMins.setOnSeekBarChangeListener(this);
		mSbCalories.setOnSeekBarChangeListener(this);
		mSbDistance.setOnSeekBarChangeListener(this);
		// mSbFloors.setOnSeekBarChangeListener(this);
		mSbSleep.setOnSeekBarChangeListener(this);
		mSbSteps.setOnSeekBarChangeListener(this);

		if (DashBoardFragment.IS_GO_FROM_DASHBOARD_TO_GOAL_PAGE) {
			/**
			 * Always set Max Goal value
			 */
			// Set initial value data for seek bar
			mSbCalories.setProgress(Integer.valueOf(DashBoardFragment.singleTon
					.getCaloriesGoalDefault()));
			mSbDistance.setProgress(Math.round(Float
					.valueOf(DashBoardFragment.singleTon
							.getDistanceGoalDefault())));
			mSbSleep.setProgress(Integer.valueOf(DashBoardFragment.singleTon
					.getSleepGoalDefault()));
			mSbSteps.setProgress(Integer.valueOf(DashBoardFragment.singleTon
					.getStepsGoalDefault()));

			// Set Goal value text
			showGoalValueFromSingleTon();

			return;
		}

		if (!mSp.getAll().isEmpty()) {
			// Set initial value data for seek bar
			mSbCalories.setProgress(Integer.valueOf(mSp.getString(
					Key.CALORIES_CURRENT, 0 + "").trim()));
			mSbDistance.setProgress(Integer.valueOf(mSp.getString(
					Key.DISTANCE_CURRENT, 0 + "").trim()));
			mSbSleep.setProgress(Integer.valueOf(mSp.getString(
					Key.SLEEP_HOURS_CONTENT, 0 + "").trim()));
			mSbSteps.setProgress(Integer.valueOf(mSp.getString(Key.STEPS_GOAL,
					0 + "").trim()));

			// Set Goal value text
			showGoalValueFromSeekBar();

			saveGoalValueIntoSingleTon();
		} else {
			mEtCalories.setText(getString(R.integer.calories_default));
			mEtDistance.setText(getString(R.integer.distance_default));
			mEtSleep.setText(getString(R.integer.sleep_default));
			mEtSteps.setText(getString(R.integer.steps_default));
		}
	}

	private void initialVariables(View v) {
		mBtnBack = (Button) v.findViewById(R.id.btn_back_in_goal);
		mBtnNext = (Button) v.findViewById(R.id.btn_next_in_goal);
		mLlIncludedButton = (LinearLayout) v
				.findViewById(R.id.ll_btn_in_goal_settings);
		mSbActiveMins = (SeekBar) v.findViewById(R.id.sb_active_mins_in_goal);
		mSbCalories = (SeekBar) v.findViewById(R.id.sb_calories_in_goal);
		mSbDistance = (SeekBar) v.findViewById(R.id.sb_distance_in_goal);
		// mSbFloors = (SeekBar) v.findViewById(R.id.sb_floors_in_goal);
		mSbSleep = (SeekBar) v.findViewById(R.id.sb_sleep_in_goal);
		mSbSteps = (SeekBar) v.findViewById(R.id.sb_steps_in_goal);
		mSpace = (Space) v.findViewById(R.id.space_bottom_in_goal_settings);
		// mTvActiveMins = (EditText)
		// v.findViewById(R.id.tv_active_mins_in_goal);
		mEtCalories = (EditText) v.findViewById(R.id.et_calories_in_goal);
		mEtDistance = (EditText) v.findViewById(R.id.et_distance_in_goal);
		// mTvFloors = (EditText) v.findViewById(R.id.tv_floors_in_goal);
		mEtSleep = (EditText) v.findViewById(R.id.et_sleep_in_goal);
		mEtSteps = (EditText) v.findViewById(R.id.et_steps_in_goal);

		mLlGoalSettings = (LinearLayout) v.findViewById(R.id.ll_goal_settings);
	}

	/**
	 * Basic methods
	 */

	public static void saveGoalValueIntoSingleTon() {
		if (DashBoardFragment.singleTon == null) {
			DashBoardFragment.singleTon = SingleTon.getInstance();
		}

		DashBoardFragment.singleTon.setCaloriesGoalDefault(mEtCalories
				.getText().toString());
		DashBoardFragment.singleTon.setDistanceGoalDefault(mEtDistance
				.getText().toString());
		DashBoardFragment.singleTon.setSleepGoalDefault(mEtSleep.getText()
				.toString());
		DashBoardFragment.singleTon.setStepsGoalDefault(mEtSteps.getText()
				.toString());
	}

	public static void saveGoalValueIntoSharedPreferences(Context context) {
		/**
		 * Save Goal value into Shared Preferences
		 */
		// We need an Editor object to make preference changes.
		// All objects are from android.context.Context
		if (mSpEditor != null) {
			if (mEtCalories != null & mEtDistance != null & mEtSleep != null
					& mEtSteps != null) {
				mSpEditor.putString(Key.CALORIES_GOAL, mEtCalories.getText()
						.toString());
				mSpEditor.putString(Key.DISTANCE_GOAL, mEtDistance.getText()
						.toString());
				mSpEditor.putString(Key.SLEEP_HOURS_CONTENT, mEtSleep.getText()
						.toString());
				mSpEditor.putString(Key.STEPS_GOAL, mEtSteps.getText()
						.toString());
			}

			// Commit the edits!
			mSpEditor.commit();
		}
	}

	private void setCursorAtFirstIndex() {
		// Set the cursor to the first index
		mEtCalories.setSelection(0);
		mEtDistance.setSelection(0);
		mEtSleep.setSelection(0);
		mEtSteps.setSelection(0);
	}

	private void setDefaultState() {
		if (Utils.checkFillBlank(mEtCalories)) {
			mEtCalories.setText("0");
		}
		if (Utils.checkFillBlank(mEtDistance)) {
			mEtDistance.setText("0");
		}
		if (Utils.checkFillBlank(mEtSleep)) {
			mEtSleep.setText("0");
		}
		if (Utils.checkFillBlank(mEtSteps)) {
			mEtSteps.setText("0");
		}

		// Set default background & color
		int color = getResources().getColor(R.color.grey_content);
		mEtCalories.setBackgroundResource(R.drawable.bg_goal_normal);
		mEtCalories.setCursorVisible(false);
		mEtCalories.setTextColor(color);
		mEtCalories.setOnFocusChangeListener(this);
		mEtCalories.setOnKeyListener(this);

		mEtDistance.setBackgroundResource(R.drawable.bg_goal_normal);
		mEtDistance.setCursorVisible(false);
		mEtDistance.setTextColor(color);
		mEtDistance.setOnFocusChangeListener(this);
		mEtDistance.setOnKeyListener(this);

		mEtSleep.setBackgroundResource(R.drawable.bg_goal_normal);
		mEtSleep.setCursorVisible(false);
		mEtSleep.setTextColor(color);
		mEtSleep.setOnFocusChangeListener(this);
		mEtSleep.setOnKeyListener(this);

		mEtSteps.setBackgroundResource(R.drawable.bg_goal_normal);
		mEtSteps.setCursorVisible(false);
		mEtSteps.setTextColor(color);
		mEtSteps.setOnFocusChangeListener(this);
		mEtSteps.setOnKeyListener(this);
	}

	private void showGoalValueFromSeekBar() {
		mEtCalories.setText(mSbCalories.getProgress() + "");
		mEtDistance.setText(mSbDistance.getProgress() + "");
		mEtSleep.setText(mSbSleep.getProgress() + "");
		mEtSteps.setText(mSbSteps.getProgress() + "");
	}

	private void showGoalValueFromSingleTon() {
		mEtCalories.setText(DashBoardFragment.singleTon
				.getCaloriesGoalDefault());
		mEtDistance.setText(DashBoardFragment.singleTon
				.getDistanceGoalDefault());
		mEtSleep.setText(DashBoardFragment.singleTon.getSleepGoalDefault());
		mEtSteps.setText(DashBoardFragment.singleTon.getStepsGoalDefault());
	}

	// @Override
	// public boolean onTouch(View v, MotionEvent event) {
	// Log.i(TAG, "onTouch");
	//
	// Utils.hideSoftKeyboard(Met);
	//
	// return false;
	// }
}
